package com.upsuns.transfer;

import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.Socket;

/**
 *@Description:<p>文件发送终端</p>
 *@author 王旭
 *@time 2016-1-30 下午5:48:55
 */
public class ClientTerminal implements Terminal {
	
	
	private String address; //接收端地址
	
	private int port; //接收端端口
	
	private Socket socket;
	
	
	public ClientTerminal(String address, int port) {
		this.address = address;
		this.port = port;
		try {
			socket = new Socket(address, port);
		} catch (IOException e) {
			System.out.println("连接失败");
			e.printStackTrace();
		}
	}
	
	
	
	@Override
	public void send(RandomAccessFile raf, long start, long len) throws IOException {
		

		byte[] buffer = new byte[1024]; //单个线程处理的文件长度的缓冲区
		
		raf.seek(start); //定位文件指针到开始位置


		OutputStream out = socket.getOutputStream(); //获取输出流
		
		int l = 0, tLen = 0;
		while((l = raf.read(buffer)) != -1) {
			out.write(buffer, 0, l);
			start += l;
			raf.seek(start);
			tLen += l;
			if(tLen >= len)
				break;
		}
		
		out.flush(); //刷新缓冲区
		
		out.close();
	}

	@Override
	public void receive(RandomAccessFile raf, long start, long len) {
		
	}
	
	public boolean isConnected() {
		return socket.isConnected();
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
	
	public Socket getSocket() {
		return socket;
	}



	public void setSocket(Socket socket) {
		this.socket = socket;
	}
	

}
